<?php
namespace app\home\service;
use app\common\model\FilmHotModel;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\GuzzleException;

class HotProcessService{

    public function getList($page_start = 0, $sort_type = '', $tag = 0, $playable = '', $type = 'movie'){
        $sort_type = empty($sort_type) ? 'recommend' : $sort_type;
        if (!isset(DoubanService::$sort_type[$sort_type])){
            return ['list' => [], 'chart' => []];
        }

        $tag = is_numeric($tag) ? DoubanService::$tag[$tag] : $tag;

        $playable = $playable == 1 ? 'on' : '';
        $listApi = str_replace(['{type}','{tag}', '{sort}', '{page_start}', '{playable}', '{size}'], [$type, $tag, $sort_type, $page_start, $playable, 20], DoubanService::API_LIST);
        $listHash = 'douban_' . md5($listApi);
        $list = cache('douban_' . $listHash);

        $doubanService = new DoubanService();
        if (!$list || true){
            $promise = $doubanService->request($listApi, null, 'get', [], true);
        }

        $chartHash = 'douban_' . md5(DoubanService::API_CHART_LIST);
        $chart = cache($chartHash);
        if (!is_array($chart)) {
            $chartResponse = $doubanService->request(DoubanService::API_CHART_LIST);
            if ($chartResponse) {
                $chart = $doubanService->parseChartListResponse($chartResponse);
                cache($chartHash, $chart, 86400);
            } else {
                $chart = [];
            }
        }

        if ($promise) {
            $listResponse = $promise->wait();
            if ($listResponse) {
                $list = $doubanService->parseListResponse($listResponse);
                cache($listHash, $list, 86400);
            } else {
                $list = [];
            }
        }


        return ['list' => $list, 'chart' => $chart];
    }


    public function getDetail($id) {
        $detailApi = str_replace('{id}', $id, DoubanService::API_DETAIL);
        $detailHash = 'douban_' . md5($detailApi);

        $doubanService = new DoubanService();

        $film = cache($detailHash);
        if (!is_array($film) || true) {
            $promise = $doubanService->request($detailApi, null, 'get', [], true);
        }

        $photosApi = str_replace(array('{id}', '{type}'), array($id, 'S'), DoubanService::API_DETAIL_PHOTOS);
        $photosHash = 'douban_' . md5($photosApi);
        $photos = cache($photosHash);
        if (!is_array($photos)) {
            $photosResponse = $doubanService->request($photosApi);
            if ($photosResponse) {
                $photos = $doubanService->parseDetailPhotosResponse($photosResponse);
                cache($photosHash, $photos, 86400);
            } else {
                $photos = [];
            }
        }

        if ($promise) {
            $detailResponse = $promise->wait();
            $detail = $doubanService->parseDetailResponse($detailResponse);
            cache($detailHash, $detail, 86400);
        }

        $detail['photos'] = array_slice($photos,0, 10);
        return $detail;
    }

    public function getDetail_v2($id) {
        $film = FilmHotModel::get($id);
        if (empty($film) || $film->isEmpty()) {
            $film = new FilmHotModel;
            $uri = "http://api.douban.com/v2/movie/subject/{$id}?apikey=0b2bdeda43b5688921839c8ecb20399b";
            $request = new Request('GET', $uri);
            $client = new Client(['timeout'  => 3.0,]);
            try {
                $response = $client->send($request);
            } catch (GuzzleException $e) {
                return $film;
            }

            $res = (string) $response->getBody();
            $res = json_decode($res, true);
            if (empty($res) || !is_array($res)) {
                return $film;
            }

            $directors = [];
            if (is_array($res['directors'])) {
                $directors = array_column($res['directors'], 'name');
            }
            $directors = json_encode($directors);

            $casts = [];
            if (is_array($res['casts'])) {
                $casts = array_column($res['casts'], 'name');
            }
            $casts = json_encode($casts);

            $writers = [];
            if (is_array($res['writers'])) {
                $writers = array_column($res['writers'], 'name');
            }
            $writers = json_encode($writers);

            $photos = [];
            if (is_array($res['photos'])) {
                $photos = array_column($res['photos'], 'image');
            }
            $photos = json_encode($photos);

            $seasons = [
                'count' => intval($res['seasons_count']),
                'current' => intval($res['current_season']),
                'episodes' => intval($res['episodes_count']),
            ];

            $res['rating']['ratings_count'] = $res['ratings_count'];
            $film->cover = $res['images']['medium'] ? $res['images']['medium'] : '';
            $film->year = intval($res['year']);
            $film->subtype = $res['subtype'];
            $film->title = $res['title'];
            $film->durations = is_array($res['durations']) ? json_encode($res['durations']) : '[]';
            $film->pubdates = is_array($res['pubdates']) ? json_encode($res['pubdates']): '[]';
            $film->languages = is_array($res['languages']) ? json_encode($res['languages']) : '[]';
            $film->genres = is_array($res['genres']) ? json_encode($res['genres']) : '[]';
            $film->directors = $directors;
            $film->casts = $casts;
            $film->writers = $writers;
            $film->summary = (string) $res['summary'];
            $film->photos = $photos;
            $film->playable = intval(is_array($res['videos']) && count($res['videos']) > 0);
            $film->videos = is_array($res['videos']) ? json_encode($res['videos']) : '[]';
            $film->rating = is_array($res['rating']) ? json_encode($res['rating']) : '[]';
            $film->seasons = json_encode($seasons);
            $film->aka = is_array($res['aka']) ? json_encode($res['aka']) : '[]';
            $film->id = $id;
            $film->isUpdate(false)->save();
        } elseif($film['playable'] != 1 && mt_rand(1, 2000) % 2 === 0 &&  (time() - strtotime($film['u_time'])) > 3600){
            $uri = "http://api.douban.com/v2/movie/subject/{$id}?apikey=0b2bdeda43b5688921839c8ecb20399b";
            $request = new Request('GET', $uri);
            $client = new Client(['timeout'  => 3.0,]);
            try {
                $response = $client->send($request);
            } catch (GuzzleException $e) {
                return $film;
            }

            $res = (string) $response->getBody();
            $res = json_decode($res, true);
            if (empty($res) || !is_array($res)) {
                return $film;
            }

            $film->playable = intval(is_array($res['videos']) && count($res['videos']) > 0);
            $film->videos = is_array($res['videos']) ? json_encode($res['videos']) : '[]';
            $film->isUpdate(false)->save();
        }
        return $film;
    }


    public function formatRatings($rating){
        $full = 200;
        $total = 0;
        foreach ($rating['details'] as $key => $value) {
            $rating['details'][$key] = [];
            $rating['details'][$key]['percent'] = 0;
            $rating['details'][$key]['score'] = $value;
            $rating['details'][$key]['width'] = 0;
            $total += $value;
        }
        foreach ($rating['details'] as $key => $value) {
            $percent = $value['score'] / $total;
            $rating['details'][$key]['width'] =  ceil($percent * $full);
            $rating['details'][$key]['percent'] = round($percent * 100, 1);
        }

        return $rating;
    }

}